package com.heima.service.impl.Sku;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.mapper.UserMapper;
import com.heima.pojo.User;
import com.heima.pojo.dto.LoginDto;
import com.heima.pojo.vo.LoginUserVo;
import com.heima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;


@Slf4j
@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, User>  implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginUserVo login(LoginDto dto) {

        if (dto == null) {
            //参数异常
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getLoginName, dto.getLoginName());
        //根据 姓名获取 user
        User user = userMapper.selectOne(wrapper);
        log.info("根据前台获取的user是={}", user);
        // new 一个loginUserVo
        LoginUserVo loginUserVo = new LoginUserVo();

        //进行加密
        String pwd = dto.getPassword();
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());

        System.out.println("pwd = " + pwd);

//        log.info("加密后的结果是={}",pwd);

//        if (user == null) { //代表用户不存在得
//        }
//    user.getPassword().equals(dto.getPassword())
//        if (!user.getPassword().equals(pwd)) { //代表密码错误
//            return null;
//        }
        //密码相等
        //根据用户名来获取region_id 和   return loginUserVo;
        //roleCode  获取角色编码
        String roleCode = user.getRoleCode();
        loginUserVo.setRoleCode(roleCode);
        //根据角色编码来判断是否是x修理员
        if (roleCode.equals("1003")) {
            loginUserVo.setRepair(true);
        } else {
            //isrepair
            loginUserVo.setRepair(false);
        }

        //获取userId
        loginUserVo.setUserId(user.getId());
        //serName
        loginUserVo.setUserName(user.getUserName());

        //是否成功
        loginUserVo.setSuccess(true);
        //msg
        loginUserVo.setMsg("登录成功");

        //Regionid
        loginUserVo.setRegionId(user.getRegionId());

        //token
//        String clientToken = dto.getClientToken();

        loginUserVo.setToken(UUID.randomUUID().toString());

        log.info("我的登录返回对象是={}", loginUserVo);

        return loginUserVo;
    }
}
